package site.luojie.business.user.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import site.luojie.business.user.controller.param.UserLoginParam;
import site.luojie.business.user.controller.param.UserRegisterParam;
import site.luojie.business.user.controller.sentinel.UserSentinel;
import site.luojie.business.user.controller.vo.UserVo;
import site.luojie.business.user.pojo.AuthUser;
import site.luojie.business.user.service.UserService;
import site.luojie.common.vo.ResultVo;

/**
 * 用户相关接口
 *
 * @author jie.luo
 * @since 2020/9/14
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 检测用户是否已注册
     */
    @GetMapping("/check/{username}")
    public ResultVo<Boolean> checkExistUser(@PathVariable String username) {
        boolean b = userService.checkExistUser(username);
        return ResultVo.ok(b);
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ResultVo<String> registry(@RequestBody UserRegisterParam param) {
        return userService.register(param);
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResultVo<UserVo> login(@RequestBody UserLoginParam param) {
        return userService.login(param);
    }

    /**
     * 检测用户是否已注册
     */
    @GetMapping("/{email}")
    @SentinelResource(
            value = "getUser",
            blockHandlerClass = UserSentinel.class,
            blockHandler = "blockException",
            fallbackClass = UserSentinel.class,
            fallback = "handlerError"
    )
    public ResultVo<AuthUser> getUser(@PathVariable String email) {
        AuthUser user = userService.getUser(email);
        return ResultVo.ok(user);
    }

    /**
     * 检测用户是否已注册
     */
    @GetMapping("/check/token")
    public ResultVo<Boolean> checkToken(@RequestParam("token") String token) {
        Boolean flag = userService.checkToken(token);
        return ResultVo.ok(flag);
    }
}
